/*
 * @Description: 登记（新增条目）弹窗
 * @Author: Rfan
 * @Date: 2022-06-17 19:46:09
 * @LastEditTime: 2023-01-06 19:09:14
 */

import { useEffect, useState } from 'react';
import { Button, Form, Modal } from 'antd';
import { LeggoForm } from '@/components/form-builder';
import type { ICommonDialog, ICoordinate } from '@/interfaces/global';

import {
  editArchiveParams,
  fetchEditDescCardForm,
  IEditDescCardFormParams
} from '@/api/archives/archives';
import { fetchDicItemListById } from '@/api/rulesettings/dictionary';
import { isNullObj, jsonClone } from '@/utils';
import { debounce } from 'lodash-es';
import { EnumInitRepoName } from '@/view/system/LIBManage/dictionaries';
import { useArchiveCollectionContext } from '../../contexts/ArchiveCollectionContext';

interface EditArchiveItemProps extends ICommonDialog {
  data: any;
  coordinate: ICoordinate;
}

const dbName = EnumInitRepoName.Collection;

const EditArchiveItem = (props: EditArchiveItemProps) => {
  const { visible, coordinate, data, onClose } = props;
  const { editArchiveItemFunc } = useArchiveCollectionContext();
  const [form] = Form.useForm();
  const leggo = LeggoForm.useLeggo();

  // 元数据及其规则列表
  const [propertyList, setPropertyList] = useState([]);
  // 分组规则，排序规则，序号规则
  const [groupSortRule, setGroupSortRule] = useState(null);

  useEffect(() => {
    if (visible) {
      console.log('level没值', coordinate);

      const params: IEditDescCardFormParams = {
        ...coordinate,
        entryId: data.id,
        dbName
      };
      fetchEditDescCardForm(params).then((res) => {
        const { cardPropertyList, descCardFormJson, entry } = res.data;
        const schemaModel = JSON.parse(descCardFormJson);
        // 渲染表单
        leggo.resetSchemaModel(schemaModel);

        setPropertyList(cardPropertyList);
        setGroupSortRule(groupSortRule);

        // 给表单赋值
        form.setFieldsValue(entry);
      });
    }
  }, [visible]);

  useEffect(() => {
    if (propertyList.length > 0) {
      propertyList.forEach((item) => {
        const { field } = item;
        if (field.dict_type_id > 0) {
          fetchDicItemListById(field.dict_type_id).then((res) => {
            const { data } = res;
            leggo.updateSchema(field.field_name, (configs) => {
              const { inputProps } = configs;
              inputProps.options = data.map((prop: any) => {
                return { label: prop.name, value: `${prop.name}:${prop.code}:${prop.value}` };
              });
            });
          });
        }
      });
    }
  }, [propertyList]);

  useEffect(() => {
    if (groupSortRule && !isNullObj(groupSortRule)) {
      const { groupFieldResultList, sortFieldResultList, triggerMode } = groupSortRule;
      if (triggerMode && !triggerMode.manualInput) {
        // 对分组字段添onChange事件加请求序号
        groupFieldResultList &&
          groupFieldResultList.forEach((item: any) => {
            leggo.updateSchema(item.fieldName, (configs) => {
              const { inputProps } = configs;
              inputProps.onChange = debounce(() => {
                getOrderNo();
              }, 300);
            });
          });

        // 对排序字段添onChange事件加请求序号
        sortFieldResultList &&
          sortFieldResultList.forEach((item: any) => {
            console.log('field_name', item.fieldName);
            leggo.updateSchema(item.fieldName, (configs) => {
              const { inputProps } = configs;
              inputProps.onChange = debounce(() => {
                getOrderNo();
              }, 300);
            });
          });

        leggo.updateSchema('arccode', (configs) => {
          const { inputProps } = configs;
          inputProps.disabled = true;
        });
      }
    }
  }, [groupSortRule]);

  /**
   * @description: 序号相关字段填写完成后查询序号
   */
  const getOrderNo = () => {
    // 表单数据
    const formData = form.getFieldsValue();
    // 分组字段，排序字段
    const { groupFieldResultList, sortFieldResultList } = groupSortRule;
    // 将分组字段与排序字段合并并去重
    const orgArr = [...(groupFieldResultList || []), ...(sortFieldResultList || [])];
    const fieldArr = orgArr.filter((item: any, index: number) => {
      return orgArr.findIndex((field) => field.fieldId === item.fieldId) === index;
    });
    // 判断相关字段是否都填写
    const finishFlag = fieldArr.every((field) => formData[field.fieldName]);

    console.log('finish', finishFlag);

    if (finishFlag) {
      //  请求序号接口
    }
  };

  /**
   * @description: 根据字段名称查找元数据及规则
   * @param {string} fieldName 字段名
   * @return {*}
   */
  const getPropertyItem = (fieldName: string) => {
    return propertyList.find((item) => item.field?.field_name === fieldName) || {};
  };

  /**
   * @description: 根据规则拼接传入字段的值
   * @param {string} fieldName
   * @return {*}
   */
  const generateFieldVal = (fieldName: string) => {
    console.log('generateFieldVal', fieldName);
    const { relationRule } = getPropertyItem(fieldName);
    if (relationRule) {
      console.log({ relationRule });
      const { dependRelationRule, relationType } = relationRule;
      if (relationType === 1) {
        // 使用 dependRelationRule 规则
        if (dependRelationRule.length > 0) {
          const str: string = dependRelationRule
            .map((rule: any) => {
              if (rule.type === 1) {
                const _fieldName = rule.fieldValue.field_name;
                let _val = form.getFieldValue(_fieldName);
                const ruleFieldItem = getPropertyItem(_fieldName);
                console.log({ ruleFieldItem });

                if (ruleFieldItem?.field?.dict_type_id > 0 && _val) {
                  [, _val] = _val.split(':');
                }
                return _val;
              }
              return rule.strValue;
            })
            .join('');
          form.setFieldsValue({ [fieldName]: str });
        }
      } else {
        // 使用 inheritRelationRule 规则
        // 理论用不上
      }
    }
  };

  const onValuesChange = (changedValues: any) => {
    console.log({ changedValues }, Object.keys(changedValues));
    const _key = Object.keys(changedValues)[0];
    const { linkageTargetFiledList } = getPropertyItem(_key);
    if (linkageTargetFiledList?.length > 0) {
      linkageTargetFiledList.forEach((item: any) => {
        if (item.level === coordinate.level) {
          generateFieldVal(item.field_name);
        }
      });
    }
  };

  // 提交表单
  const submitFunc = () => {
    form.submit();
  };

  // 新增档案类型
  const onFinish = (vals: any) => {
    const entries = Object.entries(vals).map(([k, v]: [string, any]) => {
      return {
        fieldName: k,
        fieldValue: v
      };
    });
    const params: editArchiveParams = jsonClone(coordinate);
    params.entries = entries;
    params.entryId = data.id;
    params.commonParams = {
      dbName
    };
    editArchiveItemFunc(data.id, params, data).then(() => {
      onCancel();
    });
  };

  const onCancel = () => {
    onClose();
  };

  return (
    <Modal
      destroyOnClose
      title="编辑"
      visible={visible}
      width={1000}
      onCancel={onCancel}
      footer={[
        <Button key="back" onClick={onCancel}>
          取消
        </Button>,
        <Button key="submit" type="primary" onClick={submitFunc}>
          确定
        </Button>
      ]}
    >
      <LeggoForm
        leggo={leggo}
        form={form}
        preserve={false}
        onValuesChange={onValuesChange}
        onFinish={onFinish}
      />
    </Modal>
  );
};

export default EditArchiveItem;
